/*
NAME: 
DESCRIPTION: ;
PARAMETER:
    [
		{
			name : 'step',
			title : 'step',
			type : 'LineEdit',
			property : {tool_tip : '目标step,默认是orig'},
		},
		{
			name : 'rout_shave',
			title : '外形套铜值',
			type : 'LineEdit',
			property : {tool_tip : '支持正则匹配'},
		},
		{
			name : 'npth_shave',
			title : 'Npth隔离值',
			type : 'LineEdit',
			property : {tool_tip : '支持正则匹配'},
		},
		{
			name : 'outline',
			title : '外形层',
			type : 'LineEdit',
			property : {tool_tip : '支持正则匹配'},
		},
		{
            name : 'auto_save',
			title : '自动保存',
            type : 'RadioBox',
            property : {
				item_list:[
					{name:'yes',text:'YES'},
					{name:'no',text:'NO'},
				],
				tool_tip:'是否自动保存料号开关'
			}
        }
	]
	
 VERSION_HISTORY:
	V1.00 2020-09-01 Scott Sun
	    1.新版本
		
 HELP:
 	<html><body bgcolor="#DDECFE">
		<font size="3" color="#003DB2"><p>功能简介</p></font>
		<p> 套外形 </p>
		<br>
		<font size="3" color="#003DB2"><p>参数配置</p></font>
		<p> step信息 </p>
		<br>
		<font size="3" color="#003DB2"><p>注意事项</p></font>
		<p> 无 </p>
		<br>
	</body></html>	
*/
//////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////
console.log("==============================>template");
// 引入模块 包
var $ = require('topcam.scriptfunc').argv();
var fs = require('fs');
var _ = require('lodash');
var mode = $.ikm ? "topcam" : "aimdfm";
var IKM = $.ikm; 
if (IKM==undefined ) { IKM = require('topcam.ikm6')($) }
var GEN = $.gen;
var GUI = $.gui || {};
var Job = $.job || $.job_name;
var JobId = $.job_id;
var db = $.db || IKM.db
var PAR = {}
if ($.par) {
	PAR = $.par
} else if ($.hasOwnProperty('script_parameter')){
	PAR = JSON.parse($.script_parameter);
}
if (mode === "aimdfm") {
	var database = require("topsin.database");
	database.addConnection($.conf.database_conf, "DFM");
	var QDfm = database.query("DFM");
	$.QDfm = QDfm;
	if ($.conf.product_type == "aimdfm") {
		QDfm.updateRow({
			table: "pdm_aimdfm_task",
			data: {
				current_process_title: $.process_title
			},
			where: { id: $.task_id }
		});
	}
}
var Status = 'ok';
var resultData = [];

try {
	var par = PAR;
	var default_par = {
		step: "unit.+",
		step2:"unit",
		auto_save: "No",
		rout_shave:0,
		npth_shave:0.25,
		outline:"ol",
		units:"mm"
	}
	for(var key in default_par){  // 设置默认属性
		if (!par.hasOwnProperty(key) || par[key] == ""){
			par[key] = default_par[key]
		}
	}
	if(_.isEmpty(Job)){throw "参数Job不存在"}
	var job = Job.toLowerCase()
	if(!GEN.isJobExists({job:job})){throw "料号"+job+"不存在"}
	if(!GEN.isJobOpen({job:job})){ GEN.openJob({job:job}) }
    if(mode == "aimdfm"){
        if(GEN.checkInout({job:job,mode:"test"}) != 0){ throw "the job check" }
        GEN.checkInout({job:job,mode:"out"});
	}
	
	var outResize = IKM.get_jobinfo({jobid:JobId, jobinfo:"jtg_outer_layer_avoid_copper"}) || par.rout_shave
	outResize = parseFloat(outResize)

	var n_cut = "n-cut-in"
	if(GEN.isLayerExists({job:job, layer:n_cut})){ GEN.deleteLayer({job:job,layer:[n_cut]}) }
	var matrix = GEN.getMatrix({job:job})
	var n_layers = Object.keys(matrix).sort(function(a,b){return matrix[a].row - matrix[b].row})
	.filter(function(key){
		var val = matrix[key]
		return val.layer_type == "signal" && /top|bot/.test(val.side) && val.context == "board"
	})
	var steplist = GEN.getStepList({job:job})
	steplist = steplist.filter(function(v){
		var tmpreg = new RegExp(par.step,"ig")
		return tmpreg.test(v)
	})
	if (steplist.length == 0 && par.step2) {
		steplist = GEN.getStepList({job:job}).filter(function (v) {
			var tmpreg = new RegExp(par.step2, "ig");
			return tmpreg.test(v);
		})
	}
	var rout = "ol-tz";
	if(!GEN.isLayerExists({job:job, layer:rout})){
		rout = par.outline
	}
	if(GEN.isLayerExists({job:job, layer:"ol_tz"})){
		rout = "ol_tz"
	}
	steplist.forEach(function(step) {
		GEN.openStep({job:job, name:step})
        GEN.units({type:par.units})
		GEN.clearLayers()
		if(GEN.isLayerExists({job:job,layer:"drl"})){
			// 筛选drl层上non_plated属性的物件并复制到n-cut层，resize大小设置为Npth隔离值*2000
			GEN.affectedLayer({affected:'no',mode:'all'})
			GEN.workLayer({name:"drl",display_number:2,clear_before:'yes'})
			GEN.selectByFilter({attribute:[{attribute:'.drill',option:'non_plated'}]})
			if(GEN.getSelectCount()>0){
				var resize = Number(par.npth_shave) * 2000
				GEN.COM("sel_copy_other",{dest:"layer_name",target_layer:n_cut,invert:"no",dx:0,dy:0,size:resize,x_anchor:0,y_anchor:0,rotation:0,mirror:"none"})
			}
			// 将外形上全部物件复制到n-cut层，resize大小设置为内层外形套铜值*1000 - 200。
			if(GEN.isLayerExists({job:job,layer:rout})){
				GEN.workLayer({name:rout,display_number:2,clear_before:'yes'})
				// GEN.COM("sel_change_sym",{symbol : 'r200',reset_angle : 'no'})
				GEN.COM("sel_copy_other",{dest:"layer_name",target_layer:n_cut,invert:"no",dx:0,dy:0,size:2*(outResize*1000)-200,x_anchor:0,y_anchor:0,rotation:0,mirror:"none"})
			}
			GEN.clearLayers()
			GEN.selClearFeature()
			n_layers.forEach(function(layer){
				GEN.workLayer({name:n_cut,display_number:2,clear_before:'yes'})
				GEN.selAllFeat()
				if(GEN.getSelectCount()>0){
					GEN.COM("sel_copy_other",{dest:"layer_name",target_layer:layer,invert:"yes",dx:0,dy:0,size:0,x_anchor:0,y_anchor:0,rotation:0,mirror:"none"})
				}
			})
			GEN.deleteLayer({job:job,layer:[n_cut]})
		}
	})
	

	// 保存 
	if(/yes/ig.test(par.auto_save)){
		GEN.checkInout({job:job,mode:"out"})  // 结束保存料号 关闭料号
		GEN.saveJob({ job: job });
		GEN.checkInout({job:job,mode:"in"})
		GEN.closeJob({job:job})
	} else {
		GEN.checkInout({job:job,mode:"in"})
	}

	if (mode === "aimdfm") {
		$.QDfm.updateRow({table: "pdm_aimdfm_task",data: {progress: 33.33},where: { id: $.task_id }});
		if (GEN.hasError()) {
			Status = 'error';resultData.push({ type: "error", title: "GEN错误!", detail: [{ desc: _.join(GEN.STATUS, "\n") }] });
			return {status: Status,result_data: resultData};
		} else {
			resultData.push({ type: "info", title: "操作完成, 请注意检查!" });
			return {status: Status,result_data: resultData};
		}
	}else {
		return "Done"
	}
} catch (e) {
	IKM.msg(_.join(GEN.STATUS, "\n"))
	IKM.msg(e)
    Status = 'error';
    resultData.push({type: "error", title: "脚本执行出错!", detail: [{desc: _.toString(e)}]});
    return (mode === "aimdfm") ? {status: Status, result_data: resultData} : "Error";
}
